package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequirePermission;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private IPermissionService permissionService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取登录的用户,需要强转为Employee才能操作里面的字段
        Employee employee = UserContext.getCurrentUser();
        //判断是否为管理员
        if (employee.isAdmin()) {
            //是则直接放行
            return true;
        }
        //判断请求的是静态资源还是请求路径(两者handler的类型不一样),如果是静态资源直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //将handler强转为HandlerMethod
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //判断请求路径对应的方法是否有权限注解,如果有则放行
        RequirePermission methodAnnotation = handlerMethod.getMethodAnnotation(RequirePermission.class);
        if (methodAnnotation == null) {
            //没有权限注解,放行
            return true;
        }
        //有权限注解,获取他的表达式
        String expression = methodAnnotation.expression();
        //获取这个员工的所有权限,看是否包含上述的访问的权限
        List<String> strings = UserContext.getPermissions();
        //判断是否包含
        if (strings.contains(expression)) {
            //包含则放行
            return true;
        }
        response.sendRedirect("/nopermission");
        return false;
    }
}
